package sctu.edu.java.year2016.team01.xuhanmei.day20160607.chapter15_2;

import sctu.edu.java.year2016.team01.xuhanmei.day20160610.ExerciseUDP.Receive;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;

/**
 * Created by Administrator on 2016/6/12.
 *
 */
public class TestJFrame extends JFrame implements Runnable,ActionListener{
    int port;
    InetAddress group = null;
    MulticastSocket socket = null;
    JButton run=new JButton("开始");
    JButton stop=new JButton("结束");

    JTextArea inceAr = new JTextArea(10, 10);//接收广播的文本域
    JTextArea inced = new JTextArea(10, 10);

    Thread thread;
    boolean b= false;

    public TestJFrame(){
        super("打印一句话");
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        thread = new Thread(this);
        run.addActionListener(this);
        stop.addActionListener(this);

        inceAr.setForeground(Color.BLACK);//指定文本域中文字颜色
        JPanel north = new JPanel();
        north.add(run);//将按钮添加到面板north上
        north.add(stop);
        add(north, BorderLayout.NORTH);


        JPanel South = new JPanel();
        South.setLayout(new GridLayout(1, 2));
        South.add(inceAr);
        South.add(stop);
        add(South, BorderLayout.CENTER);//设置面板布局

        validate();//刷新

        setBounds(100, 50, 360, 380);
        setVisible(true);

    }


    @Override
    public void run() {
        while (true) {

            byte data[] = new byte[1024];
            DatagramPacket packet = new DatagramPacket(data, data.length, group, port);//待接收的数据包


            try {
                socket.receive(packet);
                String message = new String(packet.getData(), 0, packet.getLength());//获取数据包中内容
                inceAr.setText("正在接收的内容：\n" + message);//将接收的内容显示在文本域中
                inced.append(message + "\n");//每条信息为一行
            } catch (Exception e) {
                e.printStackTrace();
            }


            if (b == true) {
                break;
            }

        }

    }

    @Override
    public void actionPerformed(ActionEvent e) {//单击事件

        if (e.getSource() == run) {
            run.setBackground(Color.red);//单击按钮颜色
            stop.setBackground(Color.cyan);


            if (!thread.isAlive()) {//如线程不属于新建状态
                thread = new Thread(this);
            }
            thread.start();
            b = false;

        }


        if (e.getSource() == stop) {
            run.setBackground(Color.orange);
            stop.setBackground(Color.blue);
            b = true;

        }
    }

    public static void main(String[] args) {

        Receive r = new Receive();
        r.setSize(460, 200);//设置窗体大小
    }
}
